<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/12
 * Time: 11:40
 */
namespace App\Repositories;

use App\Models\Gallery;

class GalleryRepository
{
    /**
     * @param array $params
     * @return mixed
     */
    public function create(array $params)
    {
        return Gallery::create($params);
    }

    public function update($id, $params)
    {
        return Gallery::where('id', $id)->update($params);
    }

    public function byId($id)
    {
        return Gallery::find($id);
    }

    public function destroy($id)
    {
        return Gallery::where('id', $id)->delete();
    }

    /**
     * 根据图片类型获取数据
     * @param $id
     * @return mixed
     */
    public function getByImageType($imageType, $categoryId = 0, $page = 0, $limit = 100)
    {
        $cate = empty($categoryId) ? [0] : explode(',', $categoryId);
        $page -= 1;
        $page = $page < 0 ? 0 : $page;
        $offset = $page * $limit;
        return Gallery::where([
            'image_type' => $imageType,
            'is_show' => 1,
        ])
            ->whereIn('category_id', $cate)
            ->offset($offset)
            ->limit($limit)
            ->orderBy('sort', 'asc')
            ->get();
    }

    public function getList($request)
    {
        $page = $request->pageNumber - 1;
        $page = $page < 0 ? 0 : $page;
        $limit = $request->pageSize ? $request->pageSize : 50;
        $offset = $page * $limit;
        $query = Gallery::where(function ($query) use ($request) {
            if (!empty($request->image_type)) {
                $query->where('image_type', $request->image_type);
            }
            if (!is_null($request->url_type)) {
                $query->where('url_type', $request->url_type);
            }
            if (!is_null($request->is_show)) {
                $query->where('is_show', $request->is_show);
            }
            if (!is_null($request->category_id)) {
                $query->where('category_id', $request->category_id);
            }
            if (!empty($request->keyword)) {
                switch ($request->field) {
                    case 'title':
                        $query->where('title', 'like', '%' . $request->keyword . '%');
                        break;
                    case 'remark':
                        $query->where('remark', 'like', '%' . $request->keyword . '%');
                        break;
                }
            }
        });
        $total = $query->count();
        $result = $query->latest('id')
            ->offset($offset)
            ->limit($limit)
            ->get();
        return ['result' => $result, 'count' => $total];
    }

}